<template>
  <div v-loading.fullscreen="loading">
    <el-row>
      <el-col
        :span="24"
        style="text-align:left"
      >
        <el-radio-group
          v-model="tableDatas.filters.applyType"
          @change="tableDatas.filters.applyno = ``,getTableDatas()"
        >
          <el-radio
            :value="0"
            border
          >领料单</el-radio>
          <el-radio
            :value="1"
            border
          >预留单</el-radio>
          <el-radio
            :value="3"
            border
          >采购单</el-radio>
          <el-radio
            :value="2"
            border
          >物料号</el-radio>
        </el-radio-group>
      </el-col>

      <el-col
        :span="24"
        style="text-align:left"
        class="marginTop10"
      >
        <el-input
          v-model="tableDatas.filters.applyno"
          size="large"
          @change="getTableDatas"
          clearable
        >
          <template #prepend>
            <span v-show="tableDatas.filters.applyType == 0">领料单号</span>
            <span v-show="tableDatas.filters.applyType == 1">预留单号</span>
            <span v-show="tableDatas.filters.applyType == 2">物料号</span>
            <span v-show="tableDatas.filters.applyType == 3">采购单号</span>
          </template>
        </el-input>
      </el-col>

    </el-row>

    <el-row
      :gutter="10"
      class="marginTop10"
    >
      <el-col
        :span="24"
        style="text-align:left"
      >
        <el-button
          type="success"
          @click="lightBtnClick(0,64)"
        >全部亮灯</el-button>
        <el-button
          type="success"
          @click="lightBtnClick(0,0)"
        >全部灭灯</el-button>
        <!-- <el-button
          type="primary"
          @click="lightBtnClick(1,64)"
        >选中亮灯</el-button>
        <el-button
          type="primary"
          @click="lightBtnClick(1,0)"
        >选中灭灯</el-button>
        <el-button
          type="warning"
          @click="lightBtnClick(2,32)"
        >欠缺亮灯</el-button>
        <el-button
          type="warning"
          @click="lightBtnClick(2,0)"
        >欠缺灭灯</el-button> -->
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'出库'"
      top="5vh"
      width="80vw"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <el-date-picker
              v-if="item.isDate"
              v-model="dialogDatas.currentData[item.value]"
              :type="item.dateOption ? item.dateOption.type : 'date'"
              :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
              :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
              :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
              :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
            />
            <el-switch
              v-else-if="item.isSwitch"
              v-model="dialogDatas.currentData[item.value]"
              inline-prompt
              active-text="启用"
              inactive-text="不启用"
              :active-value="item.trueValue"
              :inactive-value="item.falseValue"
            />
            <el-input
              v-else
              v-model="dialogDatas.currentData[item.value]"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.formConfirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <div
      class="marginTop10"
      v-if="tableDatas.filters.applyType != 1"
    >
      <div style="font-size:15">{{ tableDatas.currentIndex+1}} / {{ tableDatas.tableDatasAfterFilter.length}}</div>
      <el-input
        v-model="tableDatas.currentRow.LOCATIONID"
        size="large"
        disabled
      >
        <template #prepend>
          货架号
        </template>
      </el-input>
      <el-input
        v-model="tableDatas.currentRow.QRCODE"
        size="large"
        disabled
      >
        <template #prepend>
          盘号
        </template>
      </el-input>
      <el-input
        v-model="tableDatas.currentRow.useQTY"
        size="large"
        disabled
      >
        <template #prepend>
          数量
        </template>
      </el-input>

      <el-input
        v-model="tableDatas.currentRow.INPUT_LOCATIONID"
        size="large"
        @change="tableDatas.locationInputChange"
        clearable
        ref="locationIdInput"
        @focus="focusFn"
      >
        <template #prepend>
          货架号
        </template>
        <template #append>
          <span
            v-show="tableDatas.currentRow.INPUT_LOCATIONID_PASS"
            style="color:#67C23A;"
          >√√√</span>
          <span
            v-show="!tableDatas.currentRow.INPUT_LOCATIONID_PASS"
            style="color:#F56C6C"
          >×××</span>
        </template>
      </el-input>
      <el-input
        v-model="tableDatas.currentRow.INPUT_QRCODE"
        size="large"
        @change="tableDatas.matcodeInputChange"
        clearable
        ref="matcodeInput"
        @focus="focusFn"
      >
        <template #prepend>
          盘号
        </template>
        <template #append>
          <span
            v-show="tableDatas.currentRow.INPUT_QRCODE_PASS"
            style="color:#67C23A;"
          >√√√</span>
          <span
            v-show="!tableDatas.currentRow.INPUT_QRCODE_PASS"
            style="color:#F56C6C"
          >×××</span>
        </template>
      </el-input>
      <el-input
        v-model="tableDatas.currentRow.INPUT_useQTY"
        size="large"
        clearable
        @focus="focusFn"
      >
        <template #prepend>
          数量
        </template>
      </el-input>
    </div>
    <el-table
      class="marginTop10"
      v-if="tableDatas.filters.applyType == 1"
      ref="table"
      :data="tableDatas.tableDatasAfterPage"
      border
      empty-text="无数据"
      max-height="50vh"
      :row-class-name="tableDatas.tableRowClassName"
      @row-click="tableDatas.rowClick"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
        :type="column.type"
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div
      class="marginTop10"
      style="margin-bottom: 20px;"
      v-show="tableDatas.currentRow.INPUT_LOCATIONID_PASS && tableDatas.currentRow.INPUT_QRCODE_PASS"
    >
      <el-button
        type="warning"
        size="large"
        v-show="tableDatas.currentRow.matEnd"
        @click="tableDatas.rowClick(tableDatas.currentRow,{ property:'LOCATIONID' })"
      >
        拆分
      </el-button>
      <!-- <el-button
        type="primary"
        size="large"
        v-show="tableDatas.currentIndex < tableDatas.tableDatasAfterFilter.length - 1"
        @click="tableDatas.nextRowBtnClick"
      >
        下一个
      </el-button> -->
      <el-button
        type="success"
        size="large"
        v-show="tableDatas.currentRow.matEnd"
        @click="dialogDatas.confirmBtnClick"
      >
        提交
      </el-button>
    </div>
    <div
      class="marginTop10"
      v-show="tableDatas.filters.applyType == 1"
    >
      <el-button
        type="success"
        size="large"
        @click="dialogDatas.confirmBtnClick"
      >
        提交
      </el-button>
    </div>
    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import { dayjs } from 'element-plus';

import myAxios from '@/myAxios/myAxios';
import myAxiosTPX from '@/myAxios/myAxiosTPX';
import { showWarning } from '@/hooks/useMyMessageBox';
import myAxios193 from '@/myAxios/myAxios193';
import { baseUrl } from '@/myAxios/api.config';
import store from '@/store';

export default {
  name: 'LightView',
  setup () {
    let loading = ref(false);
    let table = ref(null);
    let matcodeInput = ref(null);
    let locationIdInput = ref(null);

    let lightBtnClick = function (type, colorNum) {
      if (type == 0) {
        sendLightSigns(tableDatas.tableDatasAfterFilter, colorNum);
      }
      else if (type == 1) {
        let selectDatas = table.value.getSelectionRows();
        sendLightSigns(selectDatas, colorNum);
      }
      else if (type == 2) {
        let selectDatas = tableDatas.tableDatasAfterFilter.filter(el => tableDatas.errorMatcodes.includes(el.MATCODE));
        sendLightSigns(selectDatas, colorNum);
      }
    };

    let sendLightSigns = async function (datas, colorNum) {
      // loading.value = true;

      let dataContent = {
        "Details": [
        ]
      };
      let demo = {
        "LocationId": "L8354A2055",
        "LightColor": 0,
        "Twinkle": 0,
        "IsLocked": 0,
        "IsMustCollect": 0,
        "Quantity": 5,
        "SubText": "11",
        "BatchCode": "BatchCode",
        "Name": "Name",
        "R1": "第一行",
        "R2": "第二行",
        "R3": "第三行",
        "SubTitle": "副标题",
        "Title": "主标题",
        "Unit": "单位",
        "RelateToTower": true
      };
      for (let i = 0; i < datas.length; i++) {
        let el = datas[i];
        let detail = { ...demo, LocationId: el.LOCATIONID, LightColor: colorNum };
        dataContent.Details.push(detail);
      }

      if (dataContent.Details.length) {
        if (baseUrl == 'cstApi/') {
          console.log('result :>> ', dataContent.Details, '测试默认亮灭灯成功');
        }
        else {
          let result = await myAxiosTPX.post('api/Light/PostInfo/', JSON.stringify(dataContent));
          console.log('result :>> ', result);
        }
      }
      loading.value = false;
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "LOCATIONID",
          "label": "库位号",
          "isDate": false
        },
        {
          "value": "MATCODE",
          "label": "物料号",
          "isDate": false
        },
        {
          "value": "MATNAME",
          "label": "物料描述",
          "isDate": false
        },
        {
          "value": "XLH",
          "label": "序列号",
          "isDate": false
        },
        {
          "value": "useQTY",
          "label": "出库数量",
          "isDate": false
        },
        // {
        //   "value": "ISLOCKED",
        //   "label": "是否锁定",
        //   "isDate": false
        // },
        // {
        //   "value": "MATTYPE",
        //   "label": "物料类型",
        //   "isDate": false
        // },
        // {
        //   "value": "DATA1",
        //   "label": "DATA1",
        //   "isDate": false
        // },
        // {
        //   "value": "DATA2",
        //   "label": "DATA2",
        //   "isDate": false
        // },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   }
        // },
      ],
      confirmBtnClick: async function () {
        if (tableDatas.filters.applyType == 2) {
          showWarning('查询物料号状态无法提交');
          return;
        }
        loading.value = true;

        let startIndex = tableDatas.currentIndex - tableDatas.currentRow.matLength;
        let endIndex = tableDatas.currentIndex + 1;
        let selectDatas = tableDatas.tableDatasAfterFilter.slice(startIndex, endIndex);
        if (tableDatas.filters.applyType == 1) {
          selectDatas = table.value.getSelectionRows();

        }

        let repeatParam = `${tableDatas.filters.applyno}`;
        let repeatRes = await myAxios.get('陈帅廷查询贴片线仓库重复发料记录', repeatParam);
        if (repeatRes.length) {
          let msg = `${repeatRes[0]['QRCODE']} 存在重复发料记录`;
          showWarning(msg);
          loading.value = false;
          return;
        }

        if (selectDatas.length == 0) {
          showWarning('请选择要提交的行');
          loading.value = false;
          return;
        }
        let now = dayjs().format('YYYY/MM/DD HH:mm:ss');

        // 库位状态
        let requestParamsArr = [];
        // 盘号状态
        let requestPHParamsArr = [];
        // 领料单拆分状态
        let requestSplitParamsArr = [];
        // 库位剩余数量
        let requestNumParamsArr = [];
        // 出入库记录
        let matcodeRecordParamsArr = [];
        for (let i = 0; i < selectDatas.length; i++) {
          let params = ``;
          let phParams = ``;
          let splitParams = ``;
          let numParams = ``;
          let selectDatasItem = selectDatas[i];

          // 贵重物料走DIP流程,FC开头的物料是防潮柜,走贴片料流程
          let isDIP = (tableDatas.gzMatcodeDate.includes(selectDatasItem.MATCODE)) ||
            (selectDatasItem.DIPID && !selectDatasItem.DIPID.startsWith('FC'));
          // 如果是DIP物料
          if (isDIP) {
            // 如果剩余数量等于0,库位设空,盘号设为空盘,领料单拆分设空
            if (selectDatasItem.lastQTY == 0) {
              params = `${selectDatasItem.LOCATIONID}🈹${0}`;
              phParams = `${selectDatasItem.QRCODE}🈹${0}`;
              splitParams = `${selectDatasItem.QRCODE}🈹${0}🈹${0}`;
            }
            // 剩余数量不等于0,库位设为非空
            else {
              params = `${selectDatasItem.LOCATIONID}🈹${1}`;
            }
            // 更新剩余数量
            numParams = `${selectDatasItem.LOCATIONID}🈹${selectDatasItem.lastQTY}`;
          }
          // 如果是贴片料物料
          else {
            // 如果是普通发料,直接设为空盘
            if ([0, 3].includes(tableDatas.filters.applyType)) {
              params = `${selectDatasItem.LOCATIONID}🈹${0}`;
            }
            // 如果是技术预留发料
            else if (tableDatas.filters.applyType == 1) {
              // 如果剩余数量等于0,库位设空,盘号设为空盘,领料单拆分设空
              if (selectDatasItem.lastQTY == 0) {
                params = `${selectDatasItem.LOCATIONID}🈹${0}`;
                phParams = `${selectDatasItem.QRCODE}🈹${0}`;
                splitParams = `${selectDatasItem.QRCODE}🈹${0}🈹${0}`;
              }
              // 剩余数量不等于0,库位设为非空
              else {
                console.log('selectDatas.LOCATIONID :>> ', selectDatasItem.LOCATIONID);
                params = `${selectDatasItem.LOCATIONID}🈹${1}`;
              }
              // 更新剩余数量
              numParams = `${selectDatasItem.LOCATIONID}🈹${selectDatasItem.lastQTY}`;
            }
            // params = `${selectDatasItem.LOCATIONID}🈹${0}`;
          }

          if (params) {
            requestParamsArr.push(params);
            // 绑定库位号(二合一)
            if (selectDatasItem.DATA2) {
              requestParamsArr.push(params.replace(selectDatasItem.LOCATIONID, selectDatasItem.DATA2));
            }
          }
          if (phParams) {
            requestPHParamsArr.push(phParams);
          }
          if (splitParams) {
            requestSplitParamsArr.push(splitParams);
          }
          if (numParams) {
            requestNumParamsArr.push(numParams);
            // 绑定库位号(二合一)
            if (selectDatasItem.DATA2) {
              requestNumParamsArr.push(numParams.replace(selectDatasItem.LOCATIONID, selectDatasItem.DATA2));
            }
          }

          let remark = [0, 3].includes(tableDatas.filters.applyType) ? '出库' : '预留出库';
          let sendQTY = isDIP ? selectDatasItem.useQTY : selectDatasItem.QTY;
          let sendTYPE = isDIP ? 'D' : 'T';
          let matcodeRecordParams = `${selectDatasItem.MATCODE}🈹${selectDatasItem.QRCODE}🈹${selectDatasItem.INTIME}`
            + `🈹${now}🈹${remark}🈹${selectDatasItem.useQTY}🈹${tableDatas.filters.applyno}🈹${sendQTY}🈹${sendTYPE}🈹${selectDatasItem.LOCATIONID}`;
          matcodeRecordParamsArr.push(matcodeRecordParams);
        }

        // let paramName = tableDatas.filters.applyType == 0 ? '陈帅廷修改贴片线库位状态' : '陈帅廷修改贴片线库位数量';

        let dataContent = {
          requestNames: ['陈帅廷修改贴片线库位状态', '陈帅廷修改贴片线盘号状态', '陈帅廷更新领料单拆分记录', '陈帅廷修改贴片线库位数量', '陈帅廷添加或修改贴片线出入库记录'],
          requestParamsArrs: [requestParamsArr, requestPHParamsArr, requestSplitParamsArr, requestNumParamsArr, matcodeRecordParamsArr],
          requestFactorys: ["Q902", "Q902", "Q902", "Q902", "Q902"],
        };
        // 全选而且没有物料缺失
        if ((tableDatas.currentIndex == tableDatas.tableDatasAfterFilter.length - 1) && tableDatas.errorDatas.length == 0) {
          dataContent.requestNames.push('陈帅廷修改领料单状态');
          dataContent.requestParamsArrs.push([`${tableDatas.filters.applyno}🈹${5}`]);
          dataContent.requestFactorys.push("Q902");
        }

        myAxios193.post('users/postDiffMutipleRequests', JSON.stringify(dataContent)).then(async res => {
          if (res.returnData.message.includes('全部成功')) {
            loading.value = false;

            //成功后灭灯
            dialogDatas.currentData.oriDATA2 = dialogDatas.currentData.DATA2;
            // dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!',
            });
            if (tableDatas.currentIndex != tableDatas.tableDatasAfterFilter.length - 1) {
              tableDatas.nextRowBtnClick();
            }
            else {
              sendLightSigns([tableDatas.currentRow], 0);

              tableDatas.filters.applyno = '';
              ElMessage({
                showClose: true,
                type: 'success',
                message: '领料单已完成!',
              });
              tableDatas.oritableData = [];
            }
            // dialogDatas.dialogFormVisible = false;
            // getTableDatas();

          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      formConfirmBtnClick: async function () {
        if (dialogDatas.currentData.MATCODE) {
          loading.value = true;
          let records = await myAxios.get('陈帅廷查询DIP发料记录', `${store.state.applyno}`);
          let existRecord = records.filter(el => el.XLH == dialogDatas.currentData.XLH);
          if (existRecord.length) {
            loading.value = false;
            showWarning('该空条码已绑定，无法再次绑定！');
            return;
          }
          else if (tableDatas.gzMatcodeDate.includes(dialogDatas.currentData.MATCODE)) {
            // 贵重物料序列号必须要以对应的物料号开头(因为要让贴片机识别,但是又需要拆分发料)
            if (!dialogDatas.currentData.XLH.startsWith(dialogDatas.currentData.MATCODE)) {
              loading.value = false;
              showWarning('贵重物料序列号规则不匹配，无法绑定！');
              return;
            }
          }
          let params = `${store.state.applyno}`
            + `🈹${dialogDatas.currentData.LOCATIONID}`
            + `🈹${dialogDatas.currentData.useQTY}`
            + `🈹${dialogDatas.currentData.XLH}`
            + `🈹${dialogDatas.currentData.MATCODE}`;
          myAxios.post('陈帅廷添加或修改DIP发料记录', params).then(res => {
            if (res.includes('成功')) {
              loading.value = false;
              dialogDatas.dialogFormVisible = false;
              //更新tableDatas对应行状态
              tableDatas.tableDatasAfterFilter.forEach(el => {
                if (el.LOCATIONID == dialogDatas.currentData.LOCATIONID) {
                  el.XLH = dialogDatas.currentData.XLH;
                }
              });

              ElMessage({
                showClose: true,
                type: 'success',
                message: '提交成功!'
              });
              dialogDatas.currentData = {};
            }
            else {
              loading.value = false;
              showWarning('更新失败res!' + res);
            }
          }).catch((err) => {
            loading.value = false;
            showWarning('更新失败err!' + err);
          });
        }
        else {
          showWarning('请先扫领料单!');
          loading.value = false;
        }
      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = async function () {
      //先灭灯
      sendLightSigns(tableDatas.tableDatasAfterFilter, 0);

      let gzMatcodeDate_res = await myAxios.get('陈帅廷查询贴片线贵重原材料', '');
      tableDatas.gzMatcodeDate = gzMatcodeDate_res.map(el => el.CODE);

      if (!tableDatas.filters.applyno) {
        tableDatas.oritableData = [];
        return;
        // showWarning('领料单不能为空');
      }
      else {
        loading.value = true;
        if (tableDatas.filters.applyType == 2) {
          let res = await myAxios.get('陈帅廷获取贴片线库位', tableDatas.filters.applyno);
          tableDatas.oritableData = [...res];

        }
        if (tableDatas.filters.applyType == 0) {
          if (tableDatas.filters.applyno.includes('$')) {
            let splitApplyno = tableDatas.filters.applyno.split('$');
            tableDatas.filters.applyno = splitApplyno[2];
            loading.value = false;
            getTableDatas();
            return;
          }
        }

        let lightParams = {
          "APPNO": tableDatas.filters.applyno,
          "APPTYPE": tableDatas.filters.applyType,
        };
        let res = await myAxios193.get('tpx/getLightInfo', JSON.stringify(lightParams));
        if (res.data.errorCode == 0) {
          loading.value = false;
          tableDatas.oritableData = [...res.data.lightDatas];

          if (tableDatas.filters.applyType != 1) {
            sendLightSigns([tableDatas.currentRow], 96);
          }

          store.state.applyno = tableDatas.filters.applyno;
          store.state.dipDatas = [...res.data.lightDatas].filter(el => el.DIPID);

          if (tableDatas.currentRow.DIPID) {
            tableDatas.currentRow.INPUT_LOCATIONID
              = tableDatas.currentRow.LOCATIONID;
            tableDatas.currentRow.INPUT_LOCATIONID_PASS = true;
            setTimeout(() => {
              matcodeInput.value.focus();
            }, 1);
          }
        }
        else if (res.data.errorCode == -1) {
          loading.value = false;
          showWarning('未查询到领料单物料');
        }
        else if (res.data.errorCode == -2) {
          loading.value = false;
          let errorDatas = res.data.errorDatas;
          tableDatas.errorDatas = res.data.errorDatas;
          //筛选出亮灯信息中的报错信息
          let errorMatcodes = tableDatas.errorDatas.map(el => el.MATCODE);

          let emptyStockDatas = errorDatas.filter(el => el.QTY == el.oriQTY);
          if (emptyStockDatas.length > 0) {
            showWarning(emptyStockDatas.map(el => el.MATCODE).join(',') + '库存数为0');
            let arr = errorDatas.map(el => {
              return {
                '物料号': el.MATCODE,
                '欠缺数量': el.QTY,
              };
            });
            showWarning('部分物料库存不足' + JSON.stringify(arr));
          }
          else {
            let arr = errorDatas.map(el => {
              return {
                '物料号': el.MATCODE,
                '欠缺数量': el.QTY,
              };
            });
            showWarning('部分物料库存不足' + JSON.stringify(arr));
          }
          tableDatas.oritableData = [...res.data.lightDatas];

          if (tableDatas.filters.applyType != 1) {
            sendLightSigns([tableDatas.currentRow], 96);
          }

          store.state.applyno = tableDatas.filters.applyno;
          store.state.dipDatas = [...res.data.lightDatas].filter(el => el.DIPID);

          if (tableDatas.currentRow.DIPID) {
            tableDatas.currentRow.INPUT_LOCATIONID
              = tableDatas.currentRow.LOCATIONID;
            tableDatas.currentRow.INPUT_LOCATIONID_PASS = true;
            setTimeout(() => {
              matcodeInput.value.focus();
            }, 1);
          }
        }
        locationIdInput.value.focus();
        console.log('res :>> ', res);
        // let matcodeTable = await myAxios.get('陈帅廷获取领料单物料', matcodeParams);
        // let matcodeArr = matcodeTable.map(el => el.MATCODE);

        // let length = matcodeArr.length;
        // if (length == 0) {
        //   showWarning('未查询到领料单物料');
        //   loading.value = false;
        // }
        // else {
        //   let max = 100;
        //   let count = Math.ceil(length / max);
        //   let lightDatas = [];
        //   for (let i = 0; i < count; i++) {
        //     let endIndex = length < ((i + 1) * max) ? length : ((i + 1) * max);
        //     let lightParam = matcodeArr.slice(i * 100, endIndex).join('\',\'');
        //     let lightArr = await myAxios.get('陈帅廷获取贴片线库位', lightParam);
        //     // console.log('lightArr :>> ', lightArr);
        //     lightDatas.push(...lightArr);
        //   }
        //   loading.value = false;

        //   tableDatas.oritableData = [...lightDatas];
        // }
      }
    };

    onMounted(() => {
      // getTableDatas();
    });

    let tableDatas = reactive({
      //表格样式
      tableRowClassName: function ({ row }) {
        if (row) {
          // console.log('tableDatas.errorMatcodes :>> ', tableDatas.errorMatcodes);
          console.log('row.MATCODE :>> ', row.MATCODE);
          if (tableDatas.errorMatcodes.includes(row.MATCODE)) {
            return 'warning-row';
          }
        }
      },
      currentIndex: 0,
      currentRow: computed(() => {
        if (tableDatas.tableDatasAfterFilter.length === 0) {
          return {};
        }
        return tableDatas.tableDatasAfterFilter[tableDatas.currentIndex];
      }),
      matcodeInputChange: function (newValue) {
        console.log('newValue :>> ', newValue);
        if (newValue === '') {
          tableDatas.currentRow.INPUT_QRCODE_PASS = false;
          return;
        }
        else {
          let arr = newValue.split('@');
          if (arr.length == 3) {
            tableDatas.currentRow.INPUT_QRCODE = arr[0] + '@' + arr[2];
            if (tableDatas.currentRow.INPUT_QRCODE == tableDatas.currentRow.QRCODE) {
              //正常数据
              tableDatas.currentRow.INPUT_QRCODE_PASS = true;
              tableDatas.currentRow.INPUT_useQTY = arr[1];
              if (!tableDatas.currentRow.matEnd) {
                tableDatas.nextRowBtnClick();
              }
            }
            else {
              tableDatas.currentRow.INPUT_QRCODE_PASS = false;
              showWarning('请输入正确的盘号');
            }
          }
          else {
            tableDatas.currentRow.INPUT_QRCODE_PASS = false;
            showWarning('盘号格式不正确');
            return;
          }

        }
      },
      locationInputChange: function (newValue) {
        if (newValue === '') {
          tableDatas.currentRow.INPUT_LOCATIONID_PASS = false;
          return;
        }
        else {
          if (newValue === tableDatas.currentRow.LOCATIONID) {
            //正常数据
            tableDatas.currentRow.INPUT_LOCATIONID_PASS = true;
            matcodeInput.value.focus();
          }
          else {
            tableDatas.currentRow.INPUT_LOCATIONID_PASS = false;
            showWarning('库位号不正确');
          }
        }
      },
      nextRowBtnClick: function () {
        let index = tableDatas.currentIndex + 1;
        sendLightSigns([tableDatas.currentRow], 0);
        //DIP物料不需要扫库位号
        if (tableDatas.tableDatasAfterFilter[index].DIPID) {
          tableDatas.tableDatasAfterFilter[index].INPUT_LOCATIONID
            = tableDatas.tableDatasAfterFilter[index].LOCATIONID;
          tableDatas.tableDatasAfterFilter[index].INPUT_LOCATIONID_PASS = true;
          setTimeout(() => {
            matcodeInput.value.focus();
          }, 1);
        }
        tableDatas.currentIndex = index;

        if (tableDatas.filters.applyType != 1) {
          sendLightSigns([tableDatas.currentRow], 96);
        }
      },
      //表格筛选展示相关代码
      filters: {
        applyno: '2025/07/26 15:30:00',
        applyType: 0,

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;
        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "prop": "",
          "align": "center",
          "type": "selection",
          "width": "55",
        },
        {
          "prop": "LOCATIONID",
          "label": "库位号",
          "align": "center"
        },
        // {
        //   "prop": "HJID",
        //   "label": "货架号(不一定有用)",
        //   "align": "center"
        // },
        {
          "prop": "MATCODE",
          "label": "物料号",
          "align": "center",
        },
        {
          "prop": "MATNAME",
          "label": "物料描述",
          "align": "center",
        },
        {
          "prop": "useQTY",
          "label": "数量",
          "align": "center",
        },
        // {
        //   "prop": "ISLOCKED",
        //   "label": "是否锁定",
        //   "align": "center"
        // },
        // {
        //   "prop": "MATTYPE",
        //   "label": "物料类型",
        //   "align": "center"
        // },
        // {
        //   "prop": "DATA1",
        //   "label": "DATA1",
        //   "align": "center"
        // },
        // {
        //   "prop": "DATA2",
        //   "label": "DATA2",
        //   "align": "center"
        // },
        // {
        //   "prop": "operate",
        //   "label": "操作",
        //   "align": "center",
        //   "width": 170
        // },
      ],
      oritableData: [
      ],
      errorDatas: [],
      errorMatcodes: computed(() => {
        let fData = tableDatas.errorDatas.map(el => el.MATCODE);
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),
      gzMatcodeDate: [],

      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;

        let params = ``;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },

      rowClick: function (row, column, event) {
        if (column.property == 'LOCATIONID') {
          showFormDialog(row);
          // console.log('column :>> ', column);
          // console.log('row :>> ', row);
        }
      },
    });

    let focusFn = function (event) {
      event.srcElement.setAttribute('readonly', 'readonly');
      setTimeout(() => {
        event.srcElement.removeAttribute('readonly');
      }, 200);

      // console.log('event :>> ', event);
    };

    return {
      getTableDatas,
      table,
      matcodeInput,
      locationIdInput,
      loading,
      lightBtnClick,
      dialogDatas,
      tableDatas,
      focusFn,
    };
  }
}
</script>
<style lang="css" scope>
.warning-row {
  background-color: var(--el-color-warning) !important;
}
.marginTop10 {
  margin-top: 10px;
}
</style>

